home *** CD-ROM | disk | FTP | other *** search
/ Komputer for Alle 1999 #5 / 1999 CD 5 (black).iso / Delphi3 / INFO / EXTRAS / ZLIB / ZLIB.PAS < prev   
Encoding:
Pascal/Delphi Source File  |  1997-03-24  |  15.8 KB  |  529 lines

  1. {*******************************************************}
  2. {                                                       }
  3. {       Delphi Supplemental Components                  }
  4. {       ZLIB Data Compression Interface Unit            }
  5. {                                                       }
  6. {       Copyright (c) 1997 Borland International        }
  7. {                                                       }
  8. {*******************************************************}
  9.  
  10. unit zlib;
  11.  
  12. interface
  13.  
  14. uses Sysutils, Classes;
  15.  
  16. type
  17.   TAlloc = function (AppData: Pointer; Items, Size: Integer): Pointer;
  18.   TFree = procedure (AppData, Block: Pointer);
  19.  
  20.   // Internal structure.  Ignore.
  21.   TZStreamRec = packed record
  22.     next_in: PChar;       // next input byte
  23.     avail_in: Integer;    // number of bytes available at next_in
  24.     total_in: Integer;    // total nb of input bytes read so far
  25.  
  26.     next_out: PChar;      // next output byte should be put here
  27.     avail_out: Integer;   // remaining free space at next_out
  28.     total_out: Integer;   // total nb of bytes output so far
  29.  
  30.     msg: PChar;           // last error message, NULL if no error
  31.     internal: Pointer;    // not visible by applications
  32.  
  33.     zalloc: TAlloc;       // used to allocate the internal state
  34.     zfree: TFree;         // used to free the internal state
  35.     AppData: Pointer;     // private data object passed to zalloc and zfree
  36.  
  37.     data_type: Integer;   //  best guess about the data type: ascii or binary
  38.     adler: Integer;       // adler32 value of the uncompressed data
  39.     reserved: Integer;    // reserved for future use
  40.   end;
  41.  
  42.   // Abstract ancestor class
  43.   TCustomZlibStream = class(TStream)
  44.   private
  45.     FStrm: TStream;
  46.     FStrmPos: Integer;
  47.     FOnProgress: TNotifyEvent;
  48.     FZRec: TZStreamRec;
  49.     FBuffer: array [Word] of Char;
  50.   protected
  51.     procedure Progress(Sender: TObject); dynamic;
  52.     property OnProgress: TNotifyEvent read FOnProgress write FOnProgress;
  53.     constructor Create(Strm: TStream);
  54.   end;
  55.  
  56. { TCompressionStream compresses data on the fly as data is written to it, and
  57.   stores the compressed data to another stream.
  58.  
  59.   TCompressionStream is write-only and strictly sequential. Reading from the
  60.   stream will raise an exception. Using Seek to move the stream pointer
  61.   will raise an exception.
  62.  
  63.   Output data is cached internally, written to the output stream only when
  64.   the internal output buffer is full.  All pending output data is flushed
  65.   when the stream is destroyed.
  66.  
  67.   The Position property returns the number of uncompressed bytes of
  68.   data that have been written to the stream so far.
  69.  
  70.   CompressionRate returns the on-the-fly percentage by which the original
  71.   data has been compressed:  (1 - (CompressedBytes / UncompressedBytes)) * 100
  72.   If raw data size = 100 and compressed data size = 25, the CompressionRate
  73.   is 75%
  74.  
  75.   The OnProgress event is called each time the output buffer is filled and
  76.   written to the output stream.  This is useful for updating a progress
  77.   indicator when you are writing a large chunk of data to the compression
  78.   stream in a single call.}
  79.  
  80.  
  81.   TCompressionLevel = (clNone, clFastest, clDefault, clMax);
  82.  
  83.   TCompressionStream = class(TCustomZlibStream)
  84.   private
  85.     function GetCompressionRate: Single;
  86.   public
  87.     constructor Create(CompressionLevel: TCompressionLevel; Dest: TStream);
  88.     destructor Destroy; override;
  89.     function Read(var Buffer; Count: Longint): Longint; override;
  90.     function Write(const Buffer; Count: Longint): Longint; override;
  91.     function Seek(Offset: Longint; Origin: Word): Longint; override;
  92.     property CompressionRate: Single read GetCompressionRate;
  93.     property OnProgress;
  94.   end;
  95.  
  96. { TDecompressionStream decompresses data on the fly as data is read from it.
  97.  
  98.   Compressed data comes from a separate source stream.  TDecompressionStream
  99.   is read-only and unidirectional; you can seek forward in the stream, but not
  100.   backwards.  The special case of setting the stream position to zero is
  101.   allowed.  Seeking forward decompresses data until the requested position in
  102.   the uncompressed data has been reached.  Seeking backwards, seeking relative
  103.   to the end of the stream, requesting the size of the stream, and writing to
  104.   the stream will raise an exception.
  105.  
  106.   The Position property returns the number of bytes of uncompressed data that
  107.   have been read from the stream so far.
  108.  
  109.   The OnProgress event is called each time the internal input buffer of
  110.   compressed data is exhausted and the next block is read from the input stream.
  111.   This is useful for updating a progress indicator when you are reading a
  112.   large chunk of data from the decompression stream in a single call.}
  113.  
  114.   TDecompressionStream = class(TCustomZlibStream)
  115.   public
  116.     constructor Create(Source: TStream);
  117.     destructor Destroy; override;
  118.     function Read(var Buffer; Count: Longint): Longint; override;
  119.     function Write(const Buffer; Count: Longint): Longint; override;
  120.     function Seek(Offset: Longint; Origin: Word): Longint; override;
  121.     property OnProgress;
  122.   end;
  123.  
  124.  
  125.  
  126. { CompressBuf compresses data, buffer to buffer, in one call.
  127.    In: InBuf = ptr to compressed data
  128.        InBytes = number of bytes in InBuf
  129.   Out: OutBuf = ptr to newly allocated buffer containing decompressed data
  130.        OutBytes = number of bytes in OutBuf   }
  131. procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
  132.                       out OutBuf: Pointer; out OutBytes: Integer);
  133.  
  134.  
  135. { DecompressBuf decompresses data, buffer to buffer, in one call.
  136.    In: InBuf = ptr to compressed data
  137.        InBytes = number of bytes in InBuf
  138.        OutEstimate = zero, or est. size of the decompressed data
  139.   Out: OutBuf = ptr to newly allocated buffer containing decompressed data
  140.        OutBytes = number of bytes in OutBuf   }
  141. procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
  142.  OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
  143.  
  144. const
  145.   zlib_Version = '1.0.4';
  146.  
  147. type
  148.   EZlibError = class(Exception);
  149.   ECompressionError = class(EZlibError);
  150.   EDecompressionError = class(EZlibError);
  151.  
  152. implementation
  153.  
  154. const
  155.   Z_NO_FLUSH      = 0;
  156.   Z_PARTIAL_FLUSH = 1;
  157.   Z_SYNC_FLUSH    = 2;
  158.   Z_FULL_FLUSH    = 3;
  159.   Z_FINISH        = 4;
  160.  
  161.   Z_OK            = 0;
  162.   Z_STREAM_END    = 1;
  163.   Z_NEED_DICT     = 2;
  164.   Z_ERRNO         = (-1);
  165.   Z_STREAM_ERROR  = (-2);
  166.   Z_DATA_ERROR    = (-3);
  167.   Z_MEM_ERROR     = (-4);
  168.   Z_BUF_ERROR     = (-5);
  169.   Z_VERSION_ERROR = (-6);
  170.  
  171.   Z_NO_COMPRESSION       =   0;
  172.   Z_BEST_SPEED           =   1;
  173.   Z_BEST_COMPRESSION     =   9;
  174.   Z_DEFAULT_COMPRESSION  = (-1);
  175.  
  176.   Z_FILTERED            = 1;
  177.   Z_HUFFMAN_ONLY        = 2;
  178.   Z_DEFAULT_STRATEGY    = 0;
  179.  
  180.   Z_BINARY   = 0;
  181.   Z_ASCII    = 1;
  182.   Z_UNKNOWN  = 2;
  183.  
  184.   Z_DEFLATED = 8;
  185.  
  186.  
  187.  
  188. {$L deflate.obj}
  189. {$L inflate.obj}
  190. {$L inftrees.obj}
  191. {$L trees.obj}
  192. {$L adler32.obj}
  193. {$L infblock.obj}
  194. {$L infcodes.obj}
  195. {$L infutil.obj}
  196. {$L inffast.obj}
  197.  
  198. procedure _tr_init; external;
  199. procedure _tr_tally; external;
  200. procedure _tr_flush_block; external;
  201. procedure _tr_align; external;
  202. procedure _tr_stored_block; external;
  203. procedure adler32; external;
  204. procedure inflate_blocks_new; external;
  205. procedure inflate_blocks; external;
  206. procedure inflate_blocks_reset; external;
  207. procedure inflate_blocks_free; external;
  208. procedure inflate_set_dictionary; external;
  209. procedure inflate_trees_bits; external;
  210. procedure inflate_trees_dynamic; external;
  211. procedure inflate_trees_fixed; external;
  212. procedure inflate_trees_free; external;
  213. procedure inflate_codes_new; external;
  214. procedure inflate_codes; external;
  215. procedure inflate_codes_free; external;
  216. procedure _inflate_mask; external;
  217. procedure inflate_flush; external;
  218. procedure inflate_fast; external;
  219.  
  220. procedure _memset(P: Pointer; B: Byte; count: Integer);cdecl;
  221. begin
  222.   FillChar(P^, count, B);
  223. end;
  224.  
  225. procedure _memcpy(dest, source: Pointer; count: Integer);cdecl;
  226. begin
  227.   Move(source^, dest^, count);
  228. end;
  229.  
  230.  
  231.  
  232. // deflate compresses data
  233. function deflateInit_(var strm: TZStreamRec; level: Integer; version: PChar;
  234.   recsize: Integer): Integer; external;
  235. function deflate(var strm: TZStreamRec; flush: Integer): Integer; external;
  236. function deflateEnd(var strm: TZStreamRec): Integer; external;
  237.  
  238. // inflate decompresses data
  239. function inflateInit_(var strm: TZStreamRec; version: PChar;
  240.   recsize: Integer): Integer; external;
  241. function inflate(var strm: TZStreamRec; flush: Integer): Integer; external;
  242. function inflateEnd(var strm: TZStreamRec): Integer; external;
  243. function inflateReset(var strm: TZStreamRec): Integer; external;
  244.  
  245.  
  246. function zlibAllocMem(AppData: Pointer; Items, Size: Integer): Pointer;
  247. begin
  248.   GetMem(Result, Items*Size);
  249. end;
  250.  
  251. procedure zlibFreeMem(AppData, Block: Pointer);
  252. begin
  253.   FreeMem(Block);
  254. end;
  255.  
  256. function zlibCheck(code: Integer): Integer;
  257. begin
  258.   Result := code;
  259.   if code < 0 then
  260.     raise EZlibError.Create('error');    //!!
  261. end;
  262.  
  263. function CCheck(code: Integer): Integer;
  264. begin
  265.   Result := code;
  266.   if code < 0 then
  267.     raise ECompressionError.Create('error'); //!!
  268. end;
  269.  
  270. function DCheck(code: Integer): Integer;
  271. begin
  272.   Result := code;
  273.   if code < 0 then
  274.     raise EDecompressionError.Create('error');  //!!
  275. end;
  276.  
  277. procedure CompressBuf(const InBuf: Pointer; InBytes: Integer;
  278.                       out OutBuf: Pointer; out OutBytes: Integer);
  279. var
  280.   strm: TZStreamRec;
  281.   P: Pointer;
  282. begin
  283.   FillChar(strm, sizeof(strm), 0);
  284.   strm.zalloc := zlibAllocMem;
  285.   strm.zfree := zlibFreeMem;
  286.   OutBytes := ((InBytes + (InBytes div 10) + 12) + 255) and not 255;
  287.   GetMem(OutBuf, OutBytes);
  288.   try
  289.     strm.next_in := InBuf;
  290.     strm.avail_in := InBytes;
  291.     strm.next_out := OutBuf;
  292.     strm.avail_out := OutBytes;
  293.     CCheck(deflateInit_(strm, Z_BEST_COMPRESSION, zlib_version, sizeof(strm)));
  294.     try
  295.       while CCheck(deflate(strm, Z_FINISH)) <> Z_STREAM_END do
  296.       begin
  297.         P := OutBuf;
  298.         Inc(OutBytes, 256);
  299.         ReallocMem(OutBuf, OutBytes);
  300.         strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
  301.         strm.avail_out := 256;
  302.       end;
  303.     finally
  304.       CCheck(deflateEnd(strm));
  305.     end;
  306.     ReallocMem(OutBuf, strm.total_out);
  307.     OutBytes := strm.total_out;
  308.   except
  309.     FreeMem(OutBuf);
  310.     raise
  311.   end;
  312. end;
  313.  
  314.  
  315. procedure DecompressBuf(const InBuf: Pointer; InBytes: Integer;
  316.   OutEstimate: Integer; out OutBuf: Pointer; out OutBytes: Integer);
  317. var
  318.   strm: TZStreamRec;
  319.   P: Pointer;
  320.   BufInc: Integer;
  321. begin
  322.   FillChar(strm, sizeof(strm), 0);
  323.   strm.zalloc := zlibAllocMem;
  324.   strm.zfree := zlibFreeMem;
  325.   BufInc := (InBytes + 255) and not 255;
  326.   if OutEstimate = 0 then
  327.     OutBytes := BufInc
  328.   else
  329.     OutBytes := OutEstimate;
  330.   GetMem(OutBuf, OutBytes);
  331.   try
  332.     strm.next_in := InBuf;
  333.     strm.avail_in := InBytes;
  334.     strm.next_out := OutBuf;
  335.     strm.avail_out := OutBytes;
  336.     DCheck(inflateInit_(strm, zlib_version, sizeof(strm)));
  337.     try
  338.       while DCheck(inflate(strm, Z_FINISH)) <> Z_STREAM_END do
  339.       begin
  340.         P := OutBuf;
  341.         Inc(OutBytes, BufInc);
  342.         ReallocMem(OutBuf, OutBytes);
  343.         strm.next_out := PChar(Integer(OutBuf) + (Integer(strm.next_out) - Integer(P)));
  344.         strm.avail_out := BufInc;
  345.       end;
  346.     finally
  347.       DCheck(inflateEnd(strm));
  348.     end;
  349.     ReallocMem(OutBuf, strm.total_out);
  350.     OutBytes := strm.total_out;
  351.   except
  352.     FreeMem(OutBuf);
  353.     raise
  354.   end;
  355. end;
  356.  
  357.  
  358. // TCustomZlibStream
  359.  
  360. constructor TCustomZLibStream.Create(Strm: TStream);
  361. begin
  362.   inherited Create;
  363.   FStrm := Strm;
  364.   FStrmPos := Strm.Position;
  365.   FZRec.zalloc := zlibAllocMem;
  366.   FZRec.zfree := zlibFreeMem;
  367. end;
  368.  
  369. procedure TCustomZLibStream.Progress(Sender: TObject);
  370. begin
  371.   if Assigned(FOnProgress) then FOnProgress(Sender);
  372. end;
  373.  
  374.  
  375. // TCompressionStream
  376.  
  377. constructor TCompressionStream.Create(CompressionLevel: TCompressionLevel;
  378.   Dest: TStream);
  379. const
  380.   Levels: array [TCompressionLevel] of ShortInt =
  381.     (Z_NO_COMPRESSION, Z_BEST_SPEED, Z_DEFAULT_COMPRESSION, Z_BEST_COMPRESSION);
  382. begin
  383.   inherited Create(Dest);
  384.   FZRec.next_out := FBuffer;
  385.   FZRec.avail_out := sizeof(FBuffer);
  386.   CCheck(deflateInit_(FZRec, Levels[CompressionLevel], zlib_version, sizeof(FZRec)));
  387. end;
  388.  
  389. destructor TCompressionStream.Destroy;
  390. begin
  391.   FZRec.next_in := nil;
  392.   FZRec.avail_in := 0;
  393.   try
  394.     if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  395.     while (CCheck(deflate(FZRec, Z_FINISH)) <> Z_STREAM_END)
  396.       and (FZRec.avail_out = 0) do
  397.     begin
  398.       FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
  399.       FZRec.next_out := FBuffer;
  400.       FZRec.avail_out := sizeof(FBuffer);
  401.     end;
  402.     if FZRec.avail_out < sizeof(FBuffer) then
  403.       FStrm.WriteBuffer(FBuffer, sizeof(FBuffer) - FZRec.avail_out);
  404.   finally
  405.     deflateEnd(FZRec);
  406.   end;
  407.   inherited Destroy;
  408. end;
  409.  
  410. function TCompressionStream.Read(var Buffer; Count: Longint): Longint;
  411. begin
  412.   raise ECompressionError.Create('Invalid stream operation');
  413. end;
  414.  
  415. function TCompressionStream.Write(const Buffer; Count: Longint): Longint;
  416. begin
  417.   FZRec.next_in := @Buffer;
  418.   FZRec.avail_in := Count;
  419.   if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  420.   while (FZRec.avail_in > 0) do
  421.   begin
  422.     CCheck(deflate(FZRec, 0));
  423.     if FZRec.avail_out = 0 then
  424.     begin
  425.       FStrm.WriteBuffer(FBuffer, sizeof(FBuffer));
  426.       FZRec.next_out := FBuffer;
  427.       FZRec.avail_out := sizeof(FBuffer);
  428.       FStrmPos := FStrm.Position;
  429.       Progress(Self);
  430.     end;
  431.   end;
  432.   Result := Count;
  433. end;
  434.  
  435. function TCompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
  436. begin
  437.   if (Offset = 0) and (Origin = soFromCurrent) then
  438.     Result := FZRec.total_in
  439.   else
  440.     raise ECompressionError.Create('Invalid stream operation');
  441. end;
  442.  
  443. function TCompressionStream.GetCompressionRate: Single;
  444. begin
  445.   if FZRec.total_in = 0 then
  446.     Result := 0
  447.   else
  448.     Result := (1.0 - (FZRec.total_out / FZRec.total_in)) * 100.0;
  449. end;
  450.  
  451.  
  452. // TDecompressionStream
  453.  
  454. constructor TDecompressionStream.Create(Source: TStream);
  455. begin
  456.   inherited Create(Source);
  457.   FZRec.next_in := FBuffer;
  458.   FZRec.avail_in := 0;
  459.   DCheck(inflateInit_(FZRec, zlib_version, sizeof(FZRec)));
  460. end;
  461.  
  462. destructor TDecompressionStream.Destroy;
  463. begin
  464.   inflateEnd(FZRec);
  465.   inherited Destroy;
  466. end;
  467.  
  468. function TDecompressionStream.Read(var Buffer; Count: Longint): Longint;
  469. begin
  470.   FZRec.next_out := @Buffer;
  471.   FZRec.avail_out := Count;
  472.   if FStrm.Position <> FStrmPos then FStrm.Position := FStrmPos;
  473.   while (FZRec.avail_out > 0) do
  474.   begin
  475.     if FZRec.avail_in = 0 then
  476.     begin
  477.       FZRec.avail_in := FStrm.Read(FBuffer, sizeof(FBuffer));
  478.       if FZRec.avail_in = 0 then
  479.         begin
  480.           Result := Count - FZRec.avail_out;
  481.           Exit;
  482.         end;
  483.       FZRec.next_in := FBuffer;
  484.       FStrmPos := FStrm.Position;
  485.       Progress(Self);
  486.     end;
  487.     CCheck(inflate(FZRec, 0));
  488.   end;
  489.   Result := Count;
  490. end;
  491.  
  492. function TDecompressionStream.Write(const Buffer; Count: Longint): Longint;
  493. begin
  494.   raise EDecompressionError.Create('Invalid stream operation');
  495. end;
  496.  
  497. function TDecompressionStream.Seek(Offset: Longint; Origin: Word): Longint;
  498. var
  499.   I: Integer;
  500.   Buf: array [0..4095] of Char;
  501. begin
  502.   if (Offset = 0) and (Origin = soFromBeginning) then
  503.   begin
  504.     DCheck(inflateReset(FZRec));
  505.     FZRec.next_in := FBuffer;
  506.     FZRec.avail_in := 0;
  507.     FStrm.Position := 0;
  508.     FStrmPos := 0;
  509.   end
  510.   else if ( (Offset >= 0) and (Origin = soFromCurrent)) or
  511.           ( ((Offset - FZRec.total_out) > 0) and (Origin = soFromBeginning)) then
  512.   begin
  513.     if Origin = soFromBeginning then Dec(Offset, FZRec.total_out);
  514.     if Offset > 0 then
  515.     begin
  516.       for I := 1 to Offset div sizeof(Buf) do
  517.         ReadBuffer(Buf, sizeof(Buf));
  518.       ReadBuffer(Buf, Offset mod sizeof(Buf));
  519.     end;
  520.   end
  521.   else
  522.     raise EDecompressionError.Create('Invalid stream operation');
  523.   Result := FZRec.total_out;
  524. end;
  525.  
  526.  
  527.  
  528. end.
  529.